#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void selectSort(void *ptr, int eleSize, int eleNum, int (*compare)(void*, void*))
{
	char *temp = malloc(eleSize);

	for(int i = 0; i < eleNum; ++i)
	{
		int minOrMax = i;

		for(int j = i+1; j < eleNum; ++j)
		{
			char *pJ = (char *)ptr + j * eleSize;
			char *pMinOrMax = (char *)ptr + minOrMax * eleSize;
			if(compare(pJ, pMinOrMax))
			{
				minOrMax = j;
			}
		}


		if(minOrMax != i)
		{
			char *pMinOrMax = (char *)ptr + minOrMax * eleSize;
			char *pI = (char *)ptr + i * eleSize;
			//交换数据
			memcpy(temp, pI, eleSize);
			memcpy(pI, pMinOrMax, eleSize);
			memcpy(pMinOrMax, temp, eleSize);
		}
	}



	if(temp != NULL)
	{
		free(temp);
		temp = NULL;
	}
}

int compareInt(void *d1, void *d2)
{
	int *p1 = (int*)d1;
	int *p2 = (int*)d2;
	
	return *p1 > *p2;
}

void test01()
{
	int arr[] = { 7, 4, 9, 2, 1 };

	selectSort(arr, sizeof(int), sizeof(arr)/sizeof(int), compareInt);

	for(int i = 0; i < 5; ++i)
	{
		printf("%d ", arr[i]);
	}
	printf("\n");
}

int main(int agrc, char const *agrv[])
{
	test01();
	return 0;
}
